//
//  GCMChaoBiaoViewController.m
//  GeeCityManager
//
//  Created by 聚城科技 on 16/10/9.
//  Copyright © 2016年 聚城科技. All rights reserved.
//

#import "GCMChaoBiaoViewController.h"
#import "GCMChaoBiaoTableViewCell.h"
#import "GCMChaobiaoModel.h"
#import "PPNumberButton.h"
#import "GCMYIChaobiaoViewController.h"

@interface GCMChaoBiaoViewController ()<UITableViewDataSource, UITableViewDelegate,UIAlertViewDelegate>{
    
    NSMutableArray *_DataArray;
    NSMutableArray *_HouseArray;
    UIButton * _leftbutton;
    UIButton * _rightbutton;
    UITableView *_tableView;
    NSMutableArray *_houseArr;
    NSMutableArray *_houseidArr;
    NSMutableArray *_shifouArr;
    UITableView *_tableV;
    NSMutableArray *_dataSource;
    NSMutableArray *_subSource;
    NSInteger _currentPage;
    UIButton *_subButton;
    UILabel *_dataLabel;
    
    
    
}


@end

@implementation GCMChaoBiaoViewController

-(void)viewWillAppear:(BOOL)animated{

    [self downloadTableViewData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.isSave = @"0";
    UIButton *button = [[UIButton alloc]init];
    button.backgroundColor = [UIColor colorWithRed:0.25 green:0.44 blue:0.63 alpha:1.0];
    [button setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [button setTitle:@"抄表" forState:UIControlStateNormal];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, -20,0, 0)];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -20,0, 0)];
    //    [button setTitleColor:color forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backSave) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
//    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.frame = CGRectMake(0, 0, 60, 30);
    self.navigationItem.leftBarButtonItem = item;
    
    
    
    self.view.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    [self initData];
    [self createTitle];
    [self createTableView];
    [self createUI];
    _currentPage = 1;
    //    下拉刷新
    _tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        // 进入刷新状态后会自动调用这个block
        [self downloadTableViewData];
        [_tableV.mj_header endRefreshing];
        
    }];
    //    上拉加载
    _tableV.mj_footer  = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 进入加载状态后会自动调用这个block
        _currentPage ++;
        NSString *pageStr  = [NSString stringWithFormat:@"%ld",_currentPage];
        
        [self downloadNextPageTableViewDataWith:pageStr];
        [_tableV.mj_footer endRefreshing];
    }];

    
}
-(void)downLoadData{
//    NSLog(@"%@",xqstr);
    [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:self.biaoname Withvalid:@"2" Withpage:@"1" Success:^(id obj, NSError *err) {
        _dataSource = obj;
//        NSLog(@"/////%@",_dataSource);
        [_tableV reloadData];
    }];
}

//下拉刷新和上拉加载函数
-(void)downloadTableViewData{
    [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:self.biaoname Withvalid:self.chaobiaotype Withpage:@"1" Success:^(id obj, NSError *err) {
        _dataSource = obj;
        //        NSLog(@"/////%@",_dataSource);
        [_tableV reloadData];
    }];
    
    
}
-(void)downloadNextPageTableViewDataWith:(NSString*)pagestr{
    //    改变当前页
    //_currentPage ++;
    [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:self.biaoname Withvalid:self.chaobiaotype Withpage:pagestr Success:^(id obj, NSError *err) {
        [_dataSource addObjectsFromArray:obj];
        [_tableV reloadData];
    }];
    
}

-(void)initData{
    NSArray *arr  = @[@"全部",@"未抄",@"已抄"];
    _shifouArr = [NSMutableArray arrayWithArray:arr];
    _dataSource  = [[NSMutableArray alloc]init];
    self.chaobiaotype = @"2";
    self.biaoname = @"电表";
}

-(void)createTableView{
    
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0,50, SCREEN_WIDTH, SCREEN_HEIGHT  - 50 - 60)];
    _tableV.backgroundColor  = [UIColor redColor];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    _tableV.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    [self.view addSubview:_tableV];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GCMChaoBiaoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[GCMChaoBiaoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    [cell setBackgroundColor:[UIColor colorWithRed:.93 green:.93 blue:.93 alpha:1]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //    cell.textLabel.textColor = [UIColor colorWithRed:0.39 green:0.39 blue:0.39 alpha:1];
    GCMChaobiaoModel *chaobiaoModel = _dataSource[indexPath.row];
    [cell setTextChangedBlock:^(NSString *number) {
        chaobiaoModel.byds = number;
        chaobiaoModel.isSave = @"1";
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.erjiPage = @"1";
    [cell setChabiaoModel:chaobiaoModel];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return SCREEN_HEIGHT/3;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GCMChaobiaoModel *mod = [[GCMChaobiaoModel alloc]init];
    mod  = _dataSource[indexPath.row];
    if ([mod.valid isEqualToString:@"0"]) {
       GCMYIChaobiaoViewController *cb  = [[GCMYIChaobiaoViewController alloc]init];
//       NSLog(@"111%@",_dataSource);
        cb.dataSource = [NSMutableArray arrayWithObject:_dataSource[indexPath.row]];
       [self.navigationController pushViewController:cb animated:YES];
       UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
       backItem.title = @"修改";
       self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
       self.navigationItem.backBarButtonItem = backItem;
    }
}



-(void)createUI{
    
    
//创建头部的下拉选择框
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){0.81,0.81,0.81,1});
    
    _dataLabel = [[UILabel alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-4)/3 +1, 64, (SCREEN_WIDTH-4) /3 +2, 50)];
    _dataLabel.backgroundColor = [UIColor whiteColor];
    [_dataLabel.layer setBorderWidth:1.f];
    _dataLabel.text = self.t_date;
    _dataLabel.textColor =[UIColor lightGrayColor];
    _dataLabel.textAlignment = NSTextAlignmentCenter;
    [_dataLabel.layer setBorderColor:color];
    [self.view addSubview:_dataLabel];
    _leftbutton = [[UIButton alloc] initWithFrame:CGRectMake(1, 64, (SCREEN_WIDTH-4) /3, 50)];
    _rightbutton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-4)/3 *2+3   , 64, (SCREEN_WIDTH-4)/3 , 50)];
    _leftbutton.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    _rightbutton.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);//设置title在button上的位置（上top，左left，下bottom，右right）
    [_leftbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
//    [_leftbutton setTitle:@"单元楼座" forState:UIControlStateNormal];
//    [_rightbutton setTitle:@"是否抄表" forState:UIControlStateNormal];
    [_leftbutton setBackgroundColor:[UIColor whiteColor]];
    [_rightbutton setBackgroundColor:[UIColor whiteColor]];
    [_rightbutton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    UIImageView *rimageViwe = [[UIImageView alloc]initWithFrame:CGRectMake(_rightbutton.bounds.size.width - 40, 10, 30, 30)];
    [rimageViwe setImage:[UIImage imageNamed:@"xiala"]];
    [_rightbutton addSubview:rimageViwe];
    UIImageView *limageViwe = [[UIImageView alloc]initWithFrame:CGRectMake(_rightbutton.bounds.size.width - 40, 10, 30, 30)];
    [limageViwe setImage:[UIImage imageNamed:@"xiala"]];
    [_leftbutton addSubview:limageViwe];
    [_leftbutton.layer setBorderWidth:1.f];
    [_leftbutton.layer setBorderColor:color];
    [_leftbutton.layer setCornerRadius:0];
    [_rightbutton.layer setBorderColor:color];
    [_rightbutton.layer setBorderWidth:1.f];
    [_rightbutton.layer setCornerRadius:0];
    [_leftbutton addTarget:self action:@selector(onLeftbutton) forControlEvents:UIControlEventTouchUpInside];
    [_rightbutton addTarget:self action:@selector(onRightbutton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftbutton];
    [self.view addSubview:_rightbutton];
    
//    设置小区数据
    [GCMHostSearchHttpRequst postDataWithcourtId:self.a_id Success:^(id obj, NSError *err) {
        NSLog(@"小区%@",obj);
        _HouseArray   = obj;
        NSMutableArray *fenleiB = [[NSMutableArray alloc]init];
        NSMutableArray *fenleiid = [[NSMutableArray alloc]init];
        for (NSDictionary *dic1 in _HouseArray) {
            NSString *str =[ NSString stringWithFormat:@"%@", [dic1 valueForKey:@"name"] ];
            [fenleiB addObject:str];
            NSString *idstr =[ NSString stringWithFormat:@"%@", [dic1 valueForKey:@"id"] ];
            [fenleiid addObject:idstr];
            _houseArr = [NSMutableArray arrayWithArray:fenleiB];
            _houseidArr = [NSMutableArray arrayWithArray:fenleiid];
            [_leftbutton setTitle:_houseArr[0] forState:UIControlStateNormal];
        }
        [[NSUserDefaults standardUserDefaults]setObject:[_HouseArray[0] valueForKey:@"id"] forKey:@"cbHouse"];
        self.housename = [_HouseArray[0] valueForKey:@"id"];
        [self downLoadData];
        [_tableV reloadData];
    }];
    _leftbutton.titleLabel.font = [UIFont systemFontOfSize: 15];
    _rightbutton.titleLabel.font = [UIFont systemFontOfSize: 15];

    [_leftbutton setTitle:self.housename forState:UIControlStateNormal];
    [_rightbutton setTitle:_shifouArr[0] forState:UIControlStateNormal];
    [_tableV reloadData];
    _subButton = [[UIButton alloc]initWithFrame:CGRectMake(20, SCREEN_HEIGHT - 55, SCREEN_WIDTH - 40, 50)];
    _subButton.backgroundColor = [UIColor colorWithRed:0.25 green:0.44 blue:0.63 alpha:1];
    _subButton.layer.cornerRadius = 4;
    [_subButton setTitle:@"一键保存" forState:UIControlStateNormal];
    [_subButton addTarget:self action:@selector(saveData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_subButton];
    
//    UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 50)];
//    vi.backgroundColor = [UIColor greenColor];
//    [self.view addSubview:vi];
}

//创建头上面的
-(void)createTitle{
    
    UISegmentedControl * segmented = [[UISegmentedControl alloc] initWithItems:@[@"电表", @"水表"]];
    segmented.frame = CGRectMake(0, 0, 150, 30);
    segmented.selectedSegmentIndex = 0; //设置默认选中项
    [segmented addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged]; //添加事件
    self.navigationItem.titleView = segmented;
    
}

- (void) segmentedAction:(id)sender {
    if ([sender isKindOfClass:[UISegmentedControl class]]) {
        UISegmentedControl * segment = sender;
        if (segment.selectedSegmentIndex == 0) {
            self.biaoname = @"电表";
            [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:@"电表" Withvalid:self.chaobiaotype Withpage:@"1" Success:^(id obj, NSError *err) {
                _dataSource = obj;
                [_tableV reloadData];
            }];
        }else if (segment.selectedSegmentIndex == 1) {
            self.biaoname = @"冷水表";
            [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:@"冷水表" Withvalid:self.chaobiaotype Withpage:@"1" Success:^(id obj, NSError *err) {
                _dataSource = obj;
                [_tableV reloadData];
            }];
    }
    }
}



#pragma mark--展示下拉菜单
-(void)onLeftbutton{
    
    __weak typeof(self)weakSelf = self;
    if (!_leftmuen) {
        
        _leftmuen=[[SCXCreateAlertView alloc]initWithNameArray:_houseArr andMenuOrigin:CGPointMake(0,114 ) andMenuWidth:SCREEN_WIDTH/2 andHeight:40 andLayer:0 andTableViewBackGroundColor:[UIColor clearColor] andIsSharp:YES andType:kNavigationPop];
        _leftmuen.delegate = weakSelf;
        _leftmuen.tableViewDelegate=self;
        _leftmuen.dismiss=^(){
            [weakSelf.leftmuen removeFromSuperview];
            _leftmuen=nil;
        };
        [self.view addSubview:_leftmuen];
    }
    else{
        [_leftmuen dismissWithCompletion:^(SCXCreateAlertView *create){
            [_leftmuen removeFromSuperview];
            _leftmuen = nil;
        }];
    }
}

#pragma mark--自定义下拉菜单代理方法,点击下拉菜单某一行时候对应的响应时间，点击完成后试图要消失，用一个block通知；
-(void)tableViewDidSelectRowAtIndexPath:(NSIndexPath *)indexPath andPopType:(popType)popViewType{
    
    //改变导航栏文字
    if (popViewType == kNavigationPop) {
        [_leftbutton setTitle:_houseArr[indexPath.row] forState:UIControlStateNormal];
    }
    [[NSUserDefaults standardUserDefaults]setObject:[_HouseArray[indexPath.row] valueForKey:@"name"] forKey:@"Housename"];
    self.housename = [_HouseArray[indexPath.row] valueForKey:@"id"];
    [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:self.biaoname Withvalid:self.chaobiaotype Withpage:@"1" Success:^(id obj, NSError *err) {
        _dataSource = obj;
        [_tableV reloadData];
    }];
    
    [_leftmuen dismissWithCompletion:nil];//点击完成后视图消失;
    
}
#pragma mark---同上
-(void)onRightbutton{
    __weak typeof(self)weakSelf = self;
    if (!_rightmuen) {
        
        _rightmuen=[[SCXCreateAlertView2 alloc]initWithNameArray:_shifouArr andMenuOrigin:CGPointMake(SCREEN_WIDTH/2,114 ) andMenuWidth:SCREEN_WIDTH/2 andHeight:40 andLayer:0 andTableViewBackGroundColor:[UIColor clearColor] andIsSharp:YES andType:kNavigationPop2];
        _rightmuen.delegate = weakSelf;
        _rightmuen.tableViewDelegate=self;
        _rightmuen.dismiss=^(){
            [weakSelf.rightmuen removeFromSuperview];
            _rightmuen=nil;
        };
        [self.view addSubview:_rightmuen];
    }
    else{
        [_rightmuen dismissWithCompletion:^(SCXCreateAlertView2 *create) {
            [_rightmuen removeFromSuperview];
            _rightmuen = nil;
        }];
    }
}

-(void)secondtableViewDidSelectRowAtIndexPath:(NSIndexPath *)indexPath andPopType:(popType2)popViewType{
    //改变导航栏文字
    if (popViewType==kNavigationPop2) {
        [_rightbutton setTitle:_shifouArr[indexPath.row] forState:UIControlStateNormal];
    }
    if (indexPath.row == 1) {
        self.chaobiaotype = @"1";
        _subButton.hidden = NO;
        _tableV.frame = CGRectMake(0,50, SCREEN_WIDTH, SCREEN_HEIGHT  - 50 - 60);
    }else if(indexPath.row == 2){
        self.chaobiaotype = @"0";
        _subButton.hidden = YES;
        _tableV.frame = CGRectMake(0,50, SCREEN_WIDTH, SCREEN_HEIGHT  - 50 - 10 );
    }else if(indexPath.row == 0){
        self.chaobiaotype = @"2";
        _subButton.hidden = NO;
        _tableV.frame = CGRectMake(0,50, SCREEN_WIDTH, SCREEN_HEIGHT  - 50 - 60 );
    }
    [GCMCBLRRequst postCBLRDataWithaId:self.a_id WithbId:self.housename Withtdate:self.t_date Withbiao:self.biaoname Withvalid:self.chaobiaotype Withpage:@"1" Success:^(id obj, NSError *err) {
        _dataSource = obj;
        [_tableV reloadData];
    }];
    [_rightmuen dismissWithCompletion:nil];//点击完成后视图消失;
    
}

//一键保存数据
-(void)saveData{
    
    _subSource = [[NSMutableArray alloc]init];
//    NSLog(@"bbbb%@",_dataSource);
    for (int i = 0; i < _dataSource.count; i ++) {
        GCMChaobiaoModel *chaobiaoModel = _dataSource[i];
        
        if ([chaobiaoModel.isSave isEqualToString:@"1"]) {
            [_subSource addObject:chaobiaoModel];
            chaobiaoModel.isSave = @"0";
        }
        
//        NSLog(@"aaaaa%@",_subSource);
    }
    
    
    NSMutableDictionary *parameters= [[NSMutableDictionary alloc]init];
    NSMutableDictionary * dict  = [[NSMutableDictionary alloc]init];
    for (int i = 0; i < _subSource.count; i++) {
        
        NSString * s = [NSString stringWithFormat:@"s%d",i];
        
        GCMChaobiaoModel *chaobiaoModel = _subSource[i];
//        NSLog(@"+nihao +1+  %@",_subSource);
        NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
        NSString *zb = [NSString stringWithFormat:@"%d",[chaobiaoModel.byds intValue] - [chaobiaoModel.syds intValue]];
        NSString *money = [NSString stringWithFormat:@"%d",[zb intValue]*[chaobiaoModel.dj intValue]];
        [d setObject:chaobiaoModel.idd forKey:@"id"];
        [d setObject:money forKey:@"money"];
//        处理四舍五入
        double sss = round([chaobiaoModel.byds doubleValue]*10)/10;
        NSString *ss = [NSString stringWithFormat:@"%fd",sss];
        NSArray * arrar1 = [ss  componentsSeparatedByString:@"."];
        NSRange range2 =  NSMakeRange(0, 1);
        NSString * subStr3 = [arrar1[1] substringWithRange:range2];
        NSString * iii = [NSString stringWithFormat:@"%@.%@",arrar1[0],subStr3];
        [d setObject:iii forKey:@"byds"];
//        NSLog(@"%@",iii);
        
        [d setObject:zb forKey:@"zbl"];
        [d setObject:chaobiaoModel.valid forKey:@"valid"];
        NSString *str  = [[NSString alloc]init];
        str = [GCMCBLRRequst stringWithJsonDictionary:d];
        [dict setObject:str forKey:s];
    }
//    NSLog(@"字典  %@",dict);
    parameters[@"dataJson"] = [GCMCBLRRequst stringWithJsonDictionary:dict];
 
//    NSLog(@"+nihao +1+  %@",parameters);
    
    [GCMCBLRRequst postCBLRDataWithData:parameters Success:^(id obj, NSError *err) {
        NSMutableArray * a  = [[NSMutableArray alloc]init];
        a = obj;
        BOOL i = [a valueForKey:@"result"];
        if (1 == i){
            [ProgressHUD showSuccess:[a valueForKey:@"data"]];
            [self downloadTableViewData];
        }else{
            [ProgressHUD showError:[a valueForKey:@"error"]];
        }
    }];
//    NSDictionary * dic2  = @{@"id":@"1",@"ys":@"112222221"};
//    NSMutableDictionary * dic3  = [[NSMutableDictionary alloc]init];
//    [dic3 setObject:[GCMCBLRRequst stringWithJsonDictionary:dic2] forKey:@"s0"];
//    NSLog(@"%@",dic3);
    
}

-(void)backSave{
    for (int i = 0; i < _dataSource.count; i ++) {
        GCMChaobiaoModel *chaobiaoModel = _dataSource[i];
        if ([chaobiaoModel.isSave isEqualToString:@"1"]) {
            self.isSave = @"1";
        }
        
    }
    
    if ([self.isSave isEqualToString:@"1"]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"您还没有保存信息，确认离开？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
